// 监控视频元素
function skipAd() {
    // 查找所有视频元素
    const videos = document.querySelectorAll('video');
    videos.forEach(video => {
        // 更精确的广告检测
        const isAd = video.duration <= 60 || 
                    video.src.includes('ad') || 
                    video.getAttribute('data-ad') === 'true' ||
                    video.parentElement.classList.contains('ad-container');
        
        if (isAd && video.currentTime < video.duration) {
            // 改为跳过广告而不是移除视频
            video.currentTime = video.duration;
            video.muted = true;
            // 暂停广告播放
            video.pause();
        }
    });
}

// 增强的MutationObserver配置
const observerConfig = {
    childList: true,
    subtree: true,
    attributes: true,
    attributeFilter: ['src', 'data-ad', 'class']
};

const observer = new MutationObserver((mutations) => {
    mutations.forEach(mutation => {
        if (mutation.type === 'attributes' || 
            mutation.type === 'childList') {
            skipAd();
        }
    });
});

// 初始检查
skipAd();

// 添加事件监听器
document.addEventListener('DOMContentLoaded', skipAd);
window.addEventListener('load', skipAd);
window.addEventListener('popstate', skipAd);

// 更频繁的定时检查
setInterval(skipAd, 500);

// 处理动态加载的视频
observer.observe(document.body, observerConfig);

// 拦截广告请求
chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        if (details.url.includes('ad') || details.url.includes('youkuad')) {
            return {cancel: true};
        }
    },
    {urls: ["*://*.youku.com/*", "*://*.ykimg.com/*"]},
    ["blocking"]
);